//
//  YMHotDetailVC.m
//  VideoPic
//
//  Created by apple on 16/3/25.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "YMHotDetailVC.h"
#import "Masonry.h"
#import "CardView/YMVideoPlayer.h"
#import "CardView/YMVideoPlaySlider.h"
#import "YMModelForHotVideo.h"
#import "NetworkingHandle.h"
#import "UILabel+Font.h"
#import <YYWebImage.h>
#import "YMModelForReply.h"
#import "YMCellForHotDetail.h"

@interface YMHotDetailVC () <UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, YMVideoPlayerDelegate>

@property (weak, nonatomic) IBOutlet UIView *playView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIPanGestureRecognizer *panGesture;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *playViewHeight;
@property (nonatomic, strong) YMVideoPlaySlider *slider;
@property (nonatomic, strong) YMVideoPlayer *player;
@property (nonatomic, strong) UIButton *playButton;
@property (nonatomic, strong) UILabel *labelForCurrent;
@property (nonatomic, strong) UILabel *labelForMax;
@property (nonatomic, strong) UIView *viewForBottom;
@property (nonatomic, strong) NSTimer *hidenTimer;
@property (nonatomic, strong) UIProgressView *progress;
@property (nonatomic, strong) UIImageView *imageViewForUserFace;
@property (nonatomic, strong) UILabel *labelOfUserName;
@property (nonatomic, strong) UILabel *labelOfHot;
@property (nonatomic, strong) UILabel *labelOfTitle;
@property (nonatomic, strong) UILabel *labelOfTime;
@property (nonatomic, strong) UILabel *labelOfReply;
@property (nonatomic, strong) NSString *headerStr;
@property (nonatomic, assign) BOOL tbflag;
@property (nonatomic, strong) NSMutableArray *dataArr;
@end

@implementation YMHotDetailVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    
    [self setNeedsStatusBarAppearanceUpdate];
    
}
-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor whiteColor];
    [self handleData];
    [self createSubViews];
    __weak typeof(self) weakSelf = self;
    [[NSNotificationCenter defaultCenter] addObserverForName:@"pauseAVPlayer" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if (weakSelf.player) {
            [weakSelf.player pause];
            weakSelf.playButton.hidden = NO;
            [UIView animateWithDuration:0.5 animations:^{
                weakSelf.viewForBottom.alpha = 1;
                weakSelf.progress.alpha = 0;
            }];
        }
    }];
}

- (void)handleData {
    
    NSString *url = [NSString stringWithFormat:@"http://api.miaopai.com/m/v2_channel.json?fillType=255&likeStat=true&os=ios&scid=%@&vend=miaopai&version=6.3.1", self.model.videoID];
    NSLog(@"%@", url);
    [NetworkingHandle handleWorkData:url AndBody:nil value:nil handleBlock:^(id result) {
        NSDictionary *tempDic = [[result objectForKey:@"result"] objectForKey:@"pagedcmt"];
        NSArray *tempArr = [tempDic objectForKey:@"result"];
        self.dataArr = [NSMutableArray array];
        for (NSDictionary *dic in tempArr) {
            YMModelForReply *model = [[YMModelForReply alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArr addObject:model];
        }
        self.headerStr = [NSString stringWithFormat:@"    评论  %@", [tempDic objectForKey:@"total"]];
        
        
        [self.tableView reloadData];
    }];
    
}

- (void)createSubViews {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.playView.frame), self.view.frame.size.width, self.view.frame.size.height - self.playView.frame.size.height) style:UITableViewStylePlain];
    
    [self.view addSubview:_tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.playView.mas_bottom).equalTo(@0);
        make.left.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view.mas_bottom).equalTo(@0);
        make.right.mas_equalTo(self.view);
    }];
    
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[YMCellForHotDetail class] forCellReuseIdentifier:@"cell"];
    self.tableView.bounces = NO;
    self.tableView.rowHeight = 100;
    
#pragma mark - 播放器
    [self.player playInContainer:_playView];
    self.player.path = self.model.videoUrl;
    //暂停事件
    UITapGestureRecognizer *tapButton = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapAction:)];
    [self.playView addGestureRecognizer:tapButton];
    
    //下方进度图层
    self.viewForBottom = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.playView.frame) - 30, self.view.frame.size.width, 30)];
    [self.view addSubview:_viewForBottom];
    [self.viewForBottom mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.playView.mas_bottom);
        make.right.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, 30));
    }];
    
    UIBezierPath *backgroundPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 3, self.view.frame.size.width, 30)];
    
    self.viewForBottom.layer.shadowPath = backgroundPath.CGPath;
    self.viewForBottom.layer.shadowOpacity = 0.4;
    self.viewForBottom.layer.shadowRadius = 0;
    self.viewForBottom.layer.shadowColor = [UIColor blackColor].CGColor;
    
    
    //显示当前播放时间的label
    self.labelForCurrent = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 50, 30)];
    [self.viewForBottom addSubview:_labelForCurrent];
    self.labelForCurrent.text = @"00:00";
    self.labelForCurrent.font = [UIFont systemFontOfSize:15];
    self.labelForCurrent.textColor = [UIColor colorWithRed:0.702 green:0.702 blue:0.702 alpha:1.0];
    self.labelForCurrent.textAlignment = NSTextAlignmentRight;
    
    //显示视频时长的label
    self.labelForMax = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 50, 0, 50, 30)];
    [self.viewForBottom addSubview:_labelForMax];
    self.labelForMax.text = @"00:00";
    self.labelForMax.font = [UIFont systemFontOfSize:15];
    self.labelForMax.textColor = [UIColor colorWithRed:0.702 green:0.702 blue:0.702 alpha:1.0];
    
    
    //进度条
    self.slider = [[YMVideoPlaySlider alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.labelForCurrent.frame), 0, self.view.frame.size.width - 50 - 50, 30)];
    self.slider.thumbImage = [UIImage imageNamed:@"slider"];
    
    
    [self.slider addTarget:self action:@selector(playProgressChange:) forControlEvents:UIControlEventValueChanged];

    
    [self.viewForBottom addSubview:_slider];
    
    //播放按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.playButton.frame = CGRectMake(0, 0, 50, 50);
    [self.view addSubview:_playButton];
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.playView);
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    
    self.playButton.selected = YES;
    self.playButton.center = self.playView.center;
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateNormal];
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateSelected];
    self.playButton.userInteractionEnabled = NO;
    
    
    self.progress = [[UIProgressView alloc] init];
    [self.playView addSubview:_progress];
    self.progress.tintColor = [UIColor colorWithRed:1.0 green:0.8 blue:0.4 alpha:1.0];
    self.progress.trackTintColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.3];
    [self.progress mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.playView.mas_bottom);
        make.right.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, 2));
    }];
    
    
#pragma mark - 头部图层
    UIView *viewOfheader = [[UIView alloc] init];
    
    viewOfheader.backgroundColor = [UIColor whiteColor];
    
    UIView *viewOfContent = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 80)];
    [viewOfheader addSubview:viewOfContent];
    
    //用户头像
    self.imageViewForUserFace = [[UIImageView alloc] initWithFrame:CGRectMake(20, viewOfContent.frame.size.height / 3 / 2, viewOfContent.frame.size.height / 3 * 2, viewOfContent.frame.size.height / 3 * 2)];
    [viewOfContent addSubview:_imageViewForUserFace];
    self.imageViewForUserFace.layer.cornerRadius =  viewOfContent.frame.size.height / 3;
    self.imageViewForUserFace.layer.masksToBounds = YES;
    self.imageViewForUserFace.userInteractionEnabled = YES;
    
    
    //热门
    self.labelOfHot = [[UILabel alloc] init];
    [viewOfContent addSubview:_labelOfHot];
    self.labelOfHot.textColor = [UIColor grayColor];
    self.labelOfHot.font = [UIFont systemFontOfSize:15];
    self.labelOfHot.userInteractionEnabled = YES;
    
    
    //用户名
    self.labelOfUserName = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.imageViewForUserFace.frame) + 10, CGRectGetMinY(self.imageViewForUserFace.frame) + 5, viewOfContent.frame.size.width - CGRectGetMaxX(self.imageViewForUserFace.frame) - 20 - 110, 20)];
    [viewOfContent addSubview:self.labelOfUserName];
    self.labelOfUserName.font = [UIFont systemFontOfSize:15];
    self.labelOfUserName.userInteractionEnabled = YES;
    
    
    self.labelOfTime = [[UILabel alloc] init];
    [viewOfContent addSubview:_labelOfTime];
    self.labelOfTime.font = [UIFont systemFontOfSize:15];
    self.labelOfTime.textColor = [UIColor grayColor];

    self.labelOfTime.userInteractionEnabled = YES;

    
#pragma mark - 给上面赋值
    
    [self.imageViewForUserFace yy_setImageWithURL:[NSURL URLWithString:self.model.userFace] options:YYWebImageOptionProgressiveBlur |YYWebImageOptionSetImageWithFadeAnimation];
    
    self.labelOfUserName.text = self.model.userNick;
//    self.labelOfTitle.text = self.model.videoTitle;
    /** 设置通过搜索设置可变字符串 */
    NSString *str = [NSString stringWithFormat:@"%@ 热度", self.model.vcntNice];
    
    self.labelOfTime.text = self.model.finishTimeNice;
    self.labelOfHot.text = str;
    CGRect timeRect = [self.model.finishTimeNice boundingRectWithSize:CGSizeMake(0, 20) options:0 attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil];
    self.labelOfTime.frame = CGRectMake(CGRectGetMaxX(self.imageViewForUserFace.frame) + 10, CGRectGetMaxY(self.imageViewForUserFace.frame) - 20, timeRect.size.width, 20);
    self.labelOfHot.frame = CGRectMake(CGRectGetMaxX(self.labelOfTime.frame) + 15, CGRectGetMinY(self.labelOfTime.frame), 120, 20);
    
    //显示内容
    self.labelOfTitle = [[UILabel alloc] init];
    [viewOfContent addSubview:_labelOfTitle];
    self.labelOfTitle.font = [UIFont systemFontOfSize:18];
    self.labelOfTitle.userInteractionEnabled = YES;
    self.labelOfTitle.text = self.model.videoFTitle;
    CGRect titleRect = [self.model.videoFTitle boundingRectWithSize:CGSizeMake(viewOfContent.frame.size.width - 40, 0) options:0 attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:18]} context:nil];
    self.labelOfTitle.frame = CGRectMake(20, CGRectGetMaxY(viewOfContent.frame), viewOfContent.frame.size.width - 40, titleRect.size.height);
    viewOfheader.frame = CGRectMake(0, 0, self.view.frame.size.width, CGRectGetMaxY(self.labelOfTitle.frame) + 20);
    self.tableView.tableHeaderView = viewOfheader;
    
#pragma mark - 退后按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:backButton];
    backButton.frame = CGRectMake(10, 30, 30, 30);
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(handleBackButton) forControlEvents:UIControlEventTouchUpInside];
}

- (void)handleBackButton {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)handlePushVC:(UITapGestureRecognizer *)tap {
    
}

- (void)handleTapAction:(UITapGestureRecognizer *)tap {
    self.playButton.selected = !self.playButton.selected;
    if (_playButton.selected) {
        [self.player pause];
        self.playButton.hidden = NO;
        [UIView animateWithDuration:0.5 animations:^{
            self.viewForBottom.alpha = 1;
            self.progress.alpha = 0;
        }];
        [self.hidenTimer invalidate];
    }
    else {
        [self.player play];
        self.playButton.hidden = YES;
    }
    
}

- (void)playProgressChange:(YMVideoPlaySlider *)slider {
    [self.player moveTo:slider.value];
    self.progress.progress = slider.value;
    if (!self.playButton.selected) {
        [self.player play];
    }
}

- (YMVideoPlayer *)player {
    if (_player == nil) {
        _player = [[YMVideoPlayer alloc] init];
        _player.delegate = self;
        __weak typeof(self) weakSelf = self;
        _player.bufferProgressBlock = ^(float f) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.slider.bufferValue = f;
            });
        };
        _player.progressBlock = ^(float f) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!weakSelf.slider.slide) {
                    weakSelf.slider.value = f;
                    weakSelf.progress.progress = f;
                    
                }
            });
        };
        _player.currentTimeBlock = ^(float f) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.labelForCurrent.text = [weakSelf handleTime:f];
            });
        };
        _player.maxTimeBlock = ^(float f) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.labelForMax.text = [weakSelf handleTime:f];
            });
        };
    }
    return _player;
}

- (NSString *)handleTime:(float) f{
    int time = rint(f);
    NSString *timeStr = nil;
    if (time < 60) {
        timeStr = [NSString stringWithFormat:@"00:%02d", time];
    }else if (time < 3600){
        int minutes = time / 60;
        timeStr = [NSString stringWithFormat:@"%02d:%02d", minutes, time % 60];
    }else{
        int hours = time / 3600;
        int minutes = time / 60;
        timeStr = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, time % 60];
    }
    
    return timeStr;
}
#pragma mark - YMVideoPlayerDelegate

- (void)videoPlayerDidReadyPlay:(YMVideoPlayer *)videoPlayer {
    //    [self.player play];
    //    self.playButton.selected = YES;
    //    self.playButton.hidden = NO;
    
}

- (void)videoPlayerDidBeginPlay:(YMVideoPlayer *)videoPlayer {
    [self.hidenTimer invalidate];
    self.hidenTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(handleHideBottom) userInfo:nil repeats:NO];
}

- (void)videoPlayerDidEndPlay:(YMVideoPlayer *)videoPlayer {
    [self.player playAtTheBeginning];
    //    [self.player pause];
}

- (void)videoPlayerDidSwitchPlay:(YMVideoPlayer *)videoPlayer {
}

- (void)videoPlayerDidFailedPlay:(YMVideoPlayer *)videoPlayer {
    
}

- (void)handleHideBottom {
    [UIView animateWithDuration:0.5 animations:^{
        self.viewForBottom.alpha = 0;
        self.progress.alpha = 1;
    }];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
    view.backgroundColor = [UIColor colorWithRed:0.902 green:0.902 blue:0.902 alpha:1.0];
    self.labelOfReply = [[UILabel alloc] initWithFrame:view.bounds];
    [view addSubview:_labelOfReply];
    self.labelOfReply.text = self.headerStr;
    self.labelOfReply.textColor = [UIColor grayColor];
    self.labelOfReply.font = [UIFont systemFontOfSize:15];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YMCellForHotDetail *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.backgroundColor = [UIColor colorWithRed:0.902 green:0.902 blue:0.902 alpha:1.0];
    YMModelForReply *model = [self.dataArr objectAtIndex:indexPath.row];
    [cell handleDataWithModel:model];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    YMModelForReply *model = [self.dataArr objectAtIndex:indexPath.row];
    CGRect contentRect = [model.content boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 60 - 50, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil];   
    
    return 70 + contentRect.size.height;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    __weak typeof(self) weakSelf = self;
    if (scrollView.contentOffset.y == 0) {
        self.tableView.scrollEnabled = NO;
        [NSThread sleepForTimeInterval:0.01f];
        weakSelf.tableView.scrollEnabled = YES;

    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    __weak typeof(self) weakSelf = self;
    if (scrollView.contentOffset.y == 0) {
        
        self.playViewHeight.priority = 500;
        
        [UIView animateWithDuration:0.25 animations:^{
            [weakSelf.view layoutIfNeeded];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeAV" object:nil];
        }];
    }else {
        weakSelf.playViewHeight.priority = 751;
        
        if (scrollView.contentOffset.y > self.tableView.tableHeaderView.frame.size.height - 50) {
            self.tbflag = YES;
        }else self.tbflag = NO;
        
        if (self.tbflag) {
            [weakSelf.view layoutIfNeeded];
        }else {
            [UIView animateWithDuration:0.25 animations:^{
                [weakSelf.view layoutIfNeeded];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"changeAV" object:nil];
            }];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"pauseAVPlayer"];
    [_player clear];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
